<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="文章类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择文章类型">
            <el-option
              v-for="type in typeList"
              :key="type.id"
              :value="type.value"
              :label="type.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="queryParams.publishTime"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['system:archives:add']" type="success" @click="handleOpenDialog()">
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['system:archives:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="title" label="文章标题" prop="title" min-width="150" align="center" />
        <el-table-column key="image" label="封面图片" min-width="150" align="center">
          <template #default="{ row }">
            <el-image :src="row.image" />
          </template>
        </el-table-column>
        <el-table-column
          key="description"
          label="文章简介"
          prop="description"
          min-width="150"
          align="center"
        />
        <el-table-column label="标签页">
          <template #default="{ row }">
            <el-tag v-for="(tag, index) in row.tags" :key="index">
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          key="content"
          label="文章内容"
          prop="content"
          min-width="150"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.content"
              style="width: 240px"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column key="type" label="文章类型" prop="type" min-width="150" align="center" />
        <el-table-column
          key="publishTime"
          label="发布时间"
          prop="publishTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="revokeTime"
          label="撤回时间"
          prop="revokeTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['system:archives:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['system:archives:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 博客文章表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      top="3vh"
      width="80%"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="formData.title" placeholder="文章标题" />
        </el-form-item>

        <el-form-item label="封面图片" prop="image">
          <SingleImageUpload v-model="formData.image" />
        </el-form-item>
        <el-form-item label="文章类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择文章类型">
            <el-option
              v-for="type in typeList"
              :key="type.id"
              :value="type.value"
              :label="type.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标签列" prop="tags">
          <el-input-tag
            v-model="formData.tags"
            placeholder="请输入标签"
            aria-label="输入标签,回车键确认"
          />
        </el-form-item>
        <el-form-item label="文章简介" prop="description">
          <el-input v-model="formData.description" placeholder="文章简介" />
        </el-form-item>

        <el-form-item :inline="true" label="文章内容" prop="content">
          <MdEditor v-model="formData.content" @onUploadImg="onUploadImg" />
        </el-form-item>

        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="formData.publishTime"
            type="datetime"
            placeholder="发布时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="撤回时间" prop="revokeTime">
          <el-date-picker
            v-model="formData.revokeTime"
            type="datetime"
            placeholder="撤回时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Archives",
  inheritAttrs: false,
});

import ArchivesAPI, {
  ArchivesPageVO,
  ArchivesForm,
  ArchivesPageQuery,
} from "@/api/system/archives";
import DictDataAPI, { DictDataForm } from "@/api/system/dict-data";
import FileAPI, { FileInfo } from "@/api/file";
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ArchivesPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 博客文章表格数据
const pageData = ref<ArchivesPageVO[]>([]);

// 博客文章类型列表
const typeList = ref<DictDataForm[]>([]);
// 博客文章类型编码
const typeCode = "archives_type";

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 博客文章表单数据
const formData = reactive<ArchivesForm>({});

// 博客文章表单校验规则
const rules = reactive({
  id: [{ required: true, message: "请输入文章ID", trigger: "blur" }],
  type: [{ required: true, message: "请输入文章类型", trigger: "blur" }],
  createdBy: [{ required: true, message: "请输入创建人ID", trigger: "blur" }],
  createdAt: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  updatedBy: [{ required: true, message: "请输入更新人ID", trigger: "blur" }],
  updatedAt: [{ required: true, message: "请输入更新时间", trigger: "blur" }],
});

/** 查询博客文章 */
function handleQuery() {
  loading.value = true;
  ArchivesAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查询博客文章类型 */
function handleQueryType() {
  DictDataAPI.getOptions(typeCode)
    .then((data) => {
      typeList.value = data;
    })
    .finally(() => {});
}

/** 重置博客文章查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开博客文章弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改博客文章";
    ArchivesAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    markdownToHtml.value = "";
    dialog.title = "新增博客文章";
  }
}

/** 提交博客文章表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ArchivesAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ArchivesAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭博客文章弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除博客文章 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ArchivesAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

//markdown上传图片处理
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((resolve, reject) => {
        const formData = new FormData();
        formData.append("file", file);
        FileAPI.upload(formData)
          .then((data) => {
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    })
  );
  callback(res.map((item: FileInfo) => item.url));
};

onMounted(() => {
  handleQuery();
  handleQueryType();
});
</script>

<style lang="scss" scoped>
.preview {
  max-height: 500px;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 4px;
  background-color: #f9f9f9;
  min-height: 200px;
  overflow-y: auto;
}
</style>
